package com.lnb.web.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.lnb.common.constant.BaseConstant;
import com.lnb.common.context.ThreadLocalContext;
import com.lnb.common.enums.PlatFormEnum;
import com.lnb.common.model.TokenBaseInfo;
import com.lnb.web.utils.IPUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.jboss.logging.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * <p>
 *  自定义拦截器
 * </p>
 *
 * @author liaoningbo
 * @since 2023-12-15
 */
@Component
@Configuration
@Log4j2
public class WebInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
//        log.info("请求地址：{}， 请求方式：{}", request.getRequestURI(), request.getMethod());

        //获取请求头中的trace，放入的threadLocal中
        String traceId = request.getHeader(BaseConstant.TRACE_ID);
        if(StrUtil.isEmpty(traceId)){
            traceId = IdUtil.fastUUID();
        }
        MDC.put(BaseConstant.TRACE_ID, traceId);
        ThreadLocalContext.traceThreadLocal.set(traceId);

        String ipAddress = request.getHeader(BaseConstant.IP_ADDRESS);
        if(StrUtil.isEmpty(ipAddress)){
            ipAddress = IPUtils.getIpAddress(request);
        }
        MDC.put(BaseConstant.IP_ADDRESS, ipAddress);
        ThreadLocalContext.ipThreadLocal.set(ipAddress);

        //解析token
        String token = request.getHeader(BaseConstant.TOKEN);
        TokenBaseInfo tokenBaseInfo;
        if(StrUtil.isEmpty(token)){
            tokenBaseInfo = new TokenBaseInfo()
                    .setAdminUserId(0L)
                    .setAdminUserName("系统");
        }else{
            Boolean flag = false;
            String platForm = request.getHeader(BaseConstant.PLATFORM);
            try{
                if(StrUtil.isEmpty(platForm)){
                    flag = JWTUtil.verify(token, BaseConstant.TOKEN_KEY.getBytes());
                }else{
                    if(PlatFormEnum.SUPER.getPlatform().equals(platForm)){
                        flag = JWTUtil.verify(token, BaseConstant.SUPER_TOKEN_KEY.getBytes());
                    }
                }
            }catch (Exception e){
                flag  =  false;
            }
            if(!flag){
                tokenBaseInfo = new TokenBaseInfo()
                        .setAdminUserId(0L)
                        .setAdminUserName("系统");
            }else{
                JWT jwt = JWTUtil.parseToken(token);
                tokenBaseInfo = JSONUtil.toBean(String.valueOf(jwt.getPayload(BaseConstant.TOKEN_BEAN)), TokenBaseInfo.class);
            }
            MDC.put(BaseConstant.TOKEN, token);
            if(StrUtil.isNotEmpty(platForm)){
                MDC.put(BaseConstant.PLATFORM, platForm);
            }else{
                MDC.put(BaseConstant.PLATFORM, "");
            }

        }
        ThreadLocalContext.baseInfoThreadLocal.set(tokenBaseInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex){
        ThreadLocalContext.traceThreadLocal.remove();
        ThreadLocalContext.baseInfoThreadLocal.remove();
        ThreadLocalContext.ipThreadLocal.remove();
        MDC.clear();
    }


}
